<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
import { useUserStore } from '../plugins/pinia';
import { ElMessageBox, ElMessage } from 'element-plus';

// 获取用户存储状态
const userStore = useUserStore();
const { proxy } = getCurrentInstance();

// 创建响应式的年龄选项列表
const ageOptions = ref(Array.from({ length: 201 }, (_, index) => index));

// 创建响应式表单对象
const user = reactive({
  id: userStore.userInfo.id,
  name: userStore.userInfo.name,
  age: userStore.userInfo.age,
  gender: userStore.userInfo.gender,
  email: userStore.userInfo.email,
  password: '',
  confirmPassword: '',
});

// 创建验证规则
const rules = {
  name: [
    { required: true, message: '请注意昵称长度在3~15个字符', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' },
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' },
  ],
  age: [
    { required: true, message: '请选择年龄', trigger: 'change' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== user.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

// 提交表单的方法
const userFormRef = ref(null);
const submitForm = () => {
  if (userFormRef.value) {
    userFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const response = await proxy.$axios.put('/user', user);
          if (response.data.code) {
            success_f(response);
            proxy.$router.push({ path: '/home', query: {} });
          } else {
            fail_f(response);
          }
        } catch (error) {
          console.error('Error updating user:', error);
        }
      } else {
        console.log('修改失败，请检查输入内容');
      }
    });
  }
};

const logoff = async () => {
  try {
    await ElMessageBox.confirm('确定要注销自己的账号吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await proxy.$axios.delete(`/user/${userStore.userInfo.id}`);
    ElMessage.success('注销成功');
    window.location.reload(); // 删除之后刷新数据
  } catch (error) {
    console.info('Error deleting blog:', error);
    ElMessage.info('取消注销');
  }
};

// 成功和失败的提示消息
const success_f = (response) => {
  proxy.$message({
    message: response.data.msg,
    type: 'success',
  });
};

const fail_f = (response) => {
  proxy.$message({
    message: response.data.msg,
    type: 'error',
  });
};
//返回blogs
const goBackToBlogs = () => {
  proxy.$emit('navigateToBlogs');
};
</script>

<template>
  <div class="info-editor">
    <h2>编辑用户信息</h2>
    <el-form :model="user" :rules="rules" ref="userFormRef" label-width="100px">
      <el-form-item label="用户 ID" prop="id">
        <el-input disabled v-model="user.id"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="name">
        <el-input v-model="user.name"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="user.gender" placeholder="请选择性别">
          <el-option label="男" value="male"></el-option>
          <el-option label="女" value="female"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-select v-model="user.age" placeholder="请选择年龄">
          <el-option
            v-for="age in ageOptions"
            :key="age"
            :label="age"
            :value="age"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="user.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="user.password" type="password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="user.confirmPassword"
          type="password"
          placeholder="请确认密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存修改</el-button>
        <el-button @click="$emit('navigateTorecommend')">取消</el-button>
      </el-form-item>
    </el-form>
    <p></p>
    <el-button type="danger" class="logoff-btn" @click="logoff()">
      注销账户
    </el-button>
  </div>
</template>

<style scoped>
.info-editor {
  width: 800px;
  margin: 40px auto;
  padding: 20px 30px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input,
.el-select {
  width: 100%;
}

.el-button {
  width: 120px;
}

.el-button + .el-button {
  margin-left: 10px;
}

.logoff-btn {
  margin-top: 20px;
  display: block;
  width: 150px;
  margin-left: auto;
  margin-right: auto;
  background: #f56c6c;
  color: #fff;
}

.logoff-btn:hover {
  background: #ff4c4c;
}
</style>
